package dfbz.com.controller.loginservlet;

import dfbz.com.constant.Constance;
import dfbz.com.controller.BaseServlet;
import dfbz.com.model.User;
import dfbz.com.model.UserInfo;
import dfbz.com.service.impl.UserServiceImp;
import dfbz.com.utils.CheckStrUtil;
import dfbz.com.utils.MailUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Random;

@WebServlet("/login/*")
public class LoginServlet extends BaseServlet {

    private UserServiceImp userService = new UserServiceImp();

    /**
     * 登录
     * 如果用户存在并密码正确，则跳转主页，否则回到登录页面
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //控制层尽量只是做得到用户的信息和反馈信息的功能
        String userName = req.getParameter("form-username");
        String pwd = req.getParameter("form-password");
        String remember = req.getParameter("rem_me");
        boolean exit = false;
        //登录判断，查找是否有这个对象user
        User user = userService.findUser(userName);
        if (null != user && pwd.equals(user.getPassword())) {
            //如果用户存在且密码正确,登录成功，跳转到主页
            //设置快捷登录--cookie的设置，作用：保持7天不用登录
            if (remember != null) {
                System.out.println("记住我不为空");
                Cookie[] cookies = req.getCookies();
                //记住我已经设置过，且没有失效--重新设置时间
                if (null != cookies) {
                    for (Cookie cookie : cookies) {
                        if ("userName".equals(cookie.getName())) {
                            cookie.setMaxAge(Constance.REMEMBER_COOKIE_TIME);
                            cookie.setPath("/");
                            resp.addCookie(cookie);
                            exit = true;
                            break;
                        }
                    }
                }
                //如果第一次设置或已经失效--再创建cookie
                if (!exit) {
                    Cookie cookie = new Cookie("userName", user.getUsername());
                    //问题：cookie只在登录的主页面出现，在登录页面不出现!!!
                    cookie.setMaxAge(Constance.REMEMBER_COOKIE_TIME);
                    //解决方法：扩大cookie的存在路径---根目录
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                }
            }
            //登录成功后拿到登录者的id，方便以后的调用
            req.getSession().setAttribute("userId", user.getId());
            //session 设置10分钟失效时间（timeout）
            //req.getSession().setMaxInactiveInterval(10);

            //更新登录时间
           Boolean b = userService.updateLoginTime(user.getId());
            System.out.println("更新登录时间："+b);

            System.out.println("用户登录成功，准备跳转");
            resp.sendRedirect("/view/home");

        } else {
            resp.sendRedirect("/view/index");
        }
    }


    /**
     * 注册新用户
     * 判断注册新用户是否成功
     *
     * @param req
     * @param resp
     * @throws Exception
     */

    public void toRegister(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //控制层尽量只是做得到用户的信息和反馈信息的功能

        String email = req.getParameter("form-email");
        String username = req.getParameter("form-username");
        String paw = req.getParameter("form-password");
        String paw2 = req.getParameter("form-password2");

        if (CheckStrUtil.isEmail(email)) {
            //邮箱格式正确
            if (paw.equals(paw2)) {
                //密码相同
                User user = userService.findUser(username);
                User user2 = userService.findUserByEmail(email);
                if (user != null || user2 != null) {
                    //用户已经存在，或者邮箱重复，注册不成功
                    req.getSession().setAttribute("registerError", "用户已经存在，或者邮箱重复");
                    resp.sendRedirect("/view/register");
                } else {
                    //成功注册,将对象存入数据库，后返回登录页面
                    req.getSession().setAttribute("registerError", "注册成功");
                    System.out.println("注册成功");
                    //加入user数据库
                    User newUser = new User();
                    newUser.setEmail(email);
                    newUser.setPassword(paw);
                    newUser.setUsername(username);
                    userService.add(newUser);
                    //查找这个用户
                    User nuser = userService.findUser(username);
                    //加入user ifo 数据库(主要是更新注册时间)
                    UserInfo userInfo = new UserInfo();
                    userInfo.setRegisterTime(new Date());
                    userInfo.setUserId(nuser.getId());
                    userService.add(userInfo);
                    //问题：加入user和user_ifo表中时，可能导致用户的id对不上
                    resp.sendRedirect("/view/index");
                }
            } else {
                req.getSession().setAttribute("registerError", "两次密码输入不正确");
                System.out.println("两次密码输入不正确");
                resp.sendRedirect("/view/register");
            }
        } else {
            req.getSession().setAttribute("registerError", "邮箱格式不正确");
            System.out.println("邮箱格式不正确");
            resp.sendRedirect("/view/register");
        }
    }

    /**
     * 发送邮件
     *
     * @param req
     * @param resp
     * @throws Exception
     */

    public void sendEmail(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        Object email = req.getParameter("email");
        System.out.println("前端发来的信息：" + email);
        //判断邮箱格式
        if (CheckStrUtil.isEmail(email.toString())) {
            //发送邮件
            String uEmail = (String) email;
            //产生六位随机数的验证码
            Random ra = new Random();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 6; i++) {
                sb.append(ra.nextInt(10));
            }
            System.out.println("随机数：" + sb.toString());
            try {
                MailUtil.send(uEmail, "<小标>验证码", sb.toString(), MailUtil.UNICODE);
                req.getSession().setAttribute("cCord", sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            resp.getWriter().write("邮件已经发送");
        } else {
            resp.getWriter().write("邮箱格式错误！");
        }
    }


    /**
     * 重置密码
     * 发完邮箱后，验证验证码是否正确
     * <p>
     * 问题：前端页面信息输出，用sessionscope，用req不行；显示在前端页面后怎样清除
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    public void rePassword(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String email = req.getParameter("email");
        String checkCode = req.getParameter("checkCode");
        String newPassword = req.getParameter("newPassword");
        //判断验证码是否正确
        Object cCord = req.getSession().getAttribute("cCord");
        if (cCord != null) {
            if (cCord.equals(checkCode)) {
                //开始重置密码
                User user = userService.findUserByEmail(email);
                if (user != null) {
                    user.setPassword(newPassword);
                    userService.replacePw(user);
                    req.getSession().setAttribute("resetMsg", "重置密码成功！");

                    resp.sendRedirect("/view/index");
                } else {
                    req.getSession().setAttribute("resetMsg", "没有这个用户");
                    resp.sendRedirect("/view/forget");
                }
            } else {
                req.getSession().setAttribute("resetMsg", "验证码错误");
                resp.sendRedirect("/view/forget");
            }
        }

    }


}
